package org.rsbot.util;

import java.awt.Window;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.rsbot.gui.UpdateGUI;

/*
@Auther Sorcermus for RuneDev
 */
public class UpdateUtil {

    private static final Logger log = Logger.getLogger(UpdateUtil.class.getName());
    public static int update = -1;
    private static Window parent;
    public static UpdateGUI download = null;
    private static byte[] buffer = new byte[1024];

    public UpdateUtil(final Window parent) {
        this.parent = parent;
    }

    public void checkUpdate(final boolean checkup) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (final Exception e) {
        }
        if (GlobalConfiguration.getVersion() >= getLatestVersion()) {
            return;
        }
        if (getLatestVersion() > GlobalConfiguration.getVersion()) {
            log.info("New macro client version available!");
            update = JOptionPane.showConfirmDialog(parent,
                    "A newer version of the client is available.\n\n"
                    + " Do you wish to update?\n\n"
                    + "Choosing not to update may result\n"
                    + "in problems running the client.",
                    "Update Found", JOptionPane.YES_NO_OPTION);
            if (update != 0) {
                return;
            }
            try {
                if (update == 0) {
                    updateBot();
                }
            } catch (final Exception e) {
                log.warning("Unable to update");
            }



        }
    }

    public void download(final String address, final String localFileName) {
        OutputStream out = null;
        URLConnection conn;
        InputStream in = null;
        try {
            final URL url = new URL(address);

            out = new BufferedOutputStream(new FileOutputStream(localFileName));
            conn = url.openConnection();
            in = conn.getInputStream();

            int bytesDownloaded = 0;
            int numRead = 0;
            int totalBytes = in.available() * 3;
            while ((numRead = in.read(buffer)) != -1) {
                UpdateGUI.percent = (bytesDownloaded / totalBytes * 10);
                out.write(buffer, 0, numRead);
                UpdateGUI.jLabel3.setText(" KBs " + bytesDownloaded + " / " + totalBytes + " - " + UpdateGUI.percent + "%");
            }
        } catch (final Exception e) {
            log.info("Downloading failed! " + e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (final IOException e) {
                log.info("Downloading failed! " + e.getMessage());
            }
        }
    }

    private static int getLatestVersion() {
        try {
            InputStream is = new URL(GlobalConfiguration.Paths.URLs.VERSION).openConnection().getInputStream();

            int off = 0;
            byte[] b = new byte[2];
            while ((off += is.read(b, off, 2 - off)) != 2) {
            }

            return ((0xFF & b[0]) << 8) + (0xFF & b[1]);
        } catch (final IOException e) {
            log.info("Failed to get version information! " + e.getMessage());
            return -1;
        }
    }

    public void updateBot() {
        if (download == null) {
            download = new UpdateGUI();
        }
        final String jarNew = GlobalConfiguration.NAME + ".jar";
        download(GlobalConfiguration.Paths.URLs.DOWNLOAD, jarNew);
        final Runtime run = Runtime.getRuntime();
        try {
            run.exec("java -jar " + jarNew);
            System.exit(0);
        } catch (final IOException e) {
            log.info("Jar failed! " + e.getMessage());
        }

        return;
    }
}
